package com.example.tioServer;

import com.example.common.ServerConst;
import com.example.tioServer.handler.ServerHandlerBase;
import com.example.tioServer.handler.TioServerAioHandler;
import com.example.tioServer.listener.ServerListenerBase;
import com.example.tioServer.listener.TioServerAioListener;
import org.tio.server.ServerTioConfig;
import org.tio.server.TioServer;

import java.io.IOException;

public class ServerStarter {

    //一组连接共用的上下文对象
    public static  ServerTioConfig serverTioConfig = null;
    //tioServer对象
    private  TioServer tioServer = null;
    //有时候需要绑定ip，不需要则null
    private  String serverIp = null;
    //监听的端口
    private  int serverPort = ServerConst.PORT;

    private String serverName="tio-server";

    public ServerStarter(){

    }

    public ServerStarter(String serverName){
        this.serverName=serverName;

    }
    public ServerStarter(int serverPort){
        this.serverPort=serverPort;
    }
    public ServerStarter(String serverIp,int serverPort){
        this.serverIp=serverIp;
        this.serverPort=serverPort;
    }
    public ServerStarter(String serverName,String serverIp,int serverPort){
        this.serverName=serverName;
        this.serverIp=serverIp;
        this.serverPort=serverPort;
    }


    public void setServerListener(ServerHandlerBase handler){
        serverTioConfig = new ServerTioConfig(this.serverName, new TioServerAioHandler(handler), null);
        serverTioConfig.setHeartbeatTimeout(ServerConst.TIMEOUT);
    }
    public void setServerListener(ServerHandlerBase handler,long heartbeatTimeout){
        serverTioConfig = new ServerTioConfig(this.serverName, new TioServerAioHandler(handler), null);
        serverTioConfig.setHeartbeatTimeout(heartbeatTimeout);
    }

    public void setServerListener(ServerHandlerBase handler, ServerListenerBase listener){
        serverTioConfig = new ServerTioConfig(this.serverName, new TioServerAioHandler(handler), new TioServerAioListener(listener));
        serverTioConfig.setHeartbeatTimeout(ServerConst.TIMEOUT);
    }
    public void setServerListener(ServerHandlerBase handler, ServerListenerBase listener,long heartbeatTimeout){
        serverTioConfig = new ServerTioConfig(this.serverName, new TioServerAioHandler(handler), new TioServerAioListener(listener));
        serverTioConfig.setHeartbeatTimeout(heartbeatTimeout);
    }


    public void start(){
        try {
            tioServer = new TioServer(serverTioConfig);
            tioServer.start(serverIp, serverPort);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }











}
